# -*- coding: utf-8 -*-
# @File     : backends.py
# @Author   : bingjia
# @Time     : 2020/8/4 13:29
# @Desc     : 后台认证

import re

from datetime import timedelta
from django.conf import settings
from django.utils import timezone

from ..base.api import authentication
from ..base.utils.tokens import get_user_for_token


class Session(authentication.BaseAuthentication):
    """
    session认证，生产环境中不适用
    """
    def authenticate(self, request):
        http_request = request._request
        user = getattr(http_request, 'user', None)

        if not user or not user.is_active:
            return None

        return (user, None)


class Token(authentication.BaseAuthentication):
    """
    独立的无状态身份验证实现，与oauth2相似。（Bearer Token）
    它使用django签名框架来存储令牌中存储的信任数据。
    """

    auth_rx = re.compile(r"^Bearer (.+)$")

    def authenticate(self, request):
        if "HTTP_AUTHORIZATION" not in request.META:
            return None

        token_rx_match = self.auth_rx.search(request.META["HTTP_AUTHORIZATION"])
        if not token_rx_match:
            return None

        token = token_rx_match.group(1)
        max_age_auth_token = getattr(settings, "MAX_AGE_AUTH_TOKEN", None)
        user = get_user_for_token(token, "authentication",
                                  max_age=max_age_auth_token)

        if user.last_login is None or user.last_login < (timezone.now() - timedelta(minutes=1)):
            user.last_login = timezone.now()
            user.save(update_fields=["last_login"])

        return (user, token)

    def authenticate_header(self, request):
        return 'Bearer realm="api"'